package net.llz.controller;

import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.llz.enums.BizCodeEnum;
import net.llz.enums.SendCodeEnum;
import net.llz.service.NotifyService;
import net.llz.util.CommonUtil;
import net.llz.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.util.concurrent.TimeUnit;

@Api(tags = "通知模块")
@RestController
@RequestMapping("api/user/v1")
@Slf4j
public class NotifyContronller {

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private NotifyService notifyService;

    private static final long CAPTCHA_CODE_EXPIRED = 60 * 1000 *10;




    @ApiOperation("获取图形验证码")
    @GetMapping("captcha")
    public void getCaptcha(HttpServletResponse response, HttpServletRequest request){
        String captchaText = captchaProducer.createText();
        log.info("验证码图形",captchaText);
        String cacheKey = getCaptchaKey(request);

        //redis存储
       // redisTemplate.opsForValue().set(getCaptchaKey(request),captchaText,CAPTCHA_CODE_EXPIRED,TimeUnit.MILLISECONDS);
        redisTemplate.opsForValue().set(cacheKey,captchaText,CAPTCHA_CODE_EXPIRED,TimeUnit.MILLISECONDS);

        //测试
        String test= (String) redisTemplate.opsForValue().get(cacheKey);
        System.out.println(test);

        BufferedImage bufferedImage = captchaProducer.createImage(captchaText);
        ServletOutputStream outputStream =null;
        try {
            outputStream = response.getOutputStream();
            ImageIO.write(bufferedImage,"jpg",outputStream);
            outputStream.flush();
            outputStream.close();

        }catch (Exception e){
            log.error("获取验证码异常{}",e);
        }
    }


    @ApiOperation("发送邮箱验证码")
    @GetMapping("send_code")
    public JsonData sendRegisterCode(@RequestParam(value = "to",required = true) String to ,
                                     @RequestParam(value = "captcha" ,required = true) String captcha,
                                     HttpServletRequest request){
        String key = getCaptchaKey(request);
        String cacheCaptcha = (String) redisTemplate.opsForValue().get(key);
        System.out.println(cacheCaptcha);

        if (captcha != null && cacheCaptcha!=null && cacheCaptcha.equalsIgnoreCase(captcha)){
            redisTemplate.delete(key);
            JsonData jsonData = notifyService.sendCode(SendCodeEnum.USER_REGISTER,to);
            return jsonData;

        }else {
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR);
        }

    }

    /**
     * 设置验证码key
     * @param request
     * @return
     */
    private String getCaptchaKey(HttpServletRequest request){
        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User_Agent");
        String key ="user-service:cpatcha:"+CommonUtil.MD5(ip+userAgent);

        log.info("ip{}:",ip);
        log.info("userAgent{}:",userAgent);
        log.info("key{}:",key);
        return key;

    }



}
